//
//  LYProgressView.m
//  LYPhotoBrowser
//
//  Created by LvYuan on 16/12/12.
//  Copyright © 2016年 LvYuan. All rights reserved.
//

#import "LYProgressView.h"

@interface LYProgressView ()


@end

@implementation LYProgressView

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        self.style = LYProgressViewStyleLoopDiagram;
    }
    return self;
}

- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    [self setNeedsDisplay];
}

- (UIColor *)tintColor{
    if (!_tintColor) {
        _tintColor = [UIColor whiteColor];
    }
    return _tintColor;
}

- (void)setFrame:(CGRect)frame{
    //设置背景图为圆
    frame.size.width = 50;
    frame.size.height = 50;
    self.layer.cornerRadius = 25;
    [super setFrame:frame];
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGFloat xCenter = rect.size.width * 0.5;
    CGFloat yCenter = rect.size.height * 0.5;
    [self.tintColor set];

    switch (self.style) {
        case LYProgressViewStylePieDiagram:
        {
            self.backgroundColor = self.tintColor;
            CGFloat radius = MIN(rect.size.width * 0.5, rect.size.height * 0.5) - 1;
            
            CGFloat w = radius * 2 + 1;
            CGFloat h = w;
            CGFloat x = (rect.size.width - w) * 0.5;
            CGFloat y = (rect.size.height - h) * 0.5;
            CGContextAddEllipseInRect(ctx, CGRectMake(x, y, w, h));
            CGContextFillPath(ctx);
            
            [kProgressViewBackgroundColor_ly set];
            CGContextMoveToPoint(ctx, xCenter, yCenter);
            CGContextAddLineToPoint(ctx, xCenter, 0);
            CGFloat to = 0.05 - M_PI * 0.5 + self.progress * M_PI * 2 + 0.001; // 初始值0.05
            CGContextAddArc(ctx, xCenter, yCenter, radius, - M_PI * 0.5, to, 1);
            CGContextClosePath(ctx);
            
            CGContextFillPath(ctx);
        }
            break;
            
        default:
        {
            self.backgroundColor = kProgressViewBackgroundColor_ly;
            CGContextSetLineWidth(ctx, kProgressWidth_ly);
            CGContextSetLineCap(ctx, kCGLineCapRound);
            CGFloat to = - M_PI * 0.5 + self.progress * M_PI * 2 + 0.05; // 初始值0.05
            CGFloat radius = MIN(rect.size.width, rect.size.height) * 0.5 - kProgressViewItemMargin_ly;
            CGContextAddArc(ctx, xCenter, yCenter, radius, - M_PI * 0.5, to, 0);
            CGContextStrokePath(ctx);
        }
            break;
    }
}


@end
